package us.wili.dev.common.model.validator;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;

/**
 * Created by JasonY on 17/2/19.
 */
public class PasswordValidator implements ConstraintValidator<Password, Object> {

    /**
     * 8～16个字符，至少要有一个字母、一个数字、一个特殊符号
     */
    private final static String PASSWORD_REG = "^(?=.*[A-Za-z])(?=.*\\d)(?=.*[$@$!%*#?&.])[A-Za-z\\d$@$!%*#?&.]{8,16}$";
    private Pattern passwordPattern = Pattern.compile(PASSWORD_REG);


    @Override
    public void initialize(Password constraintAnnotation) {

    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {


        if (value == null) {
            return true;
        }

        if (!(value instanceof String)) {
            return false;
        }

        return passwordPattern.matcher(value.toString()).matches();
    }
}
